<template>
  <div id='CalcBase'>
    <Breadcrumb content='公共参数配置' />
    <div class='bodyContent'>
      <el-tabs type='border-card'>
        <el-tab-pane label='公共参数配置'>
          <Splitpanes class='area'>
            <Pane size='40'>
              <vxe-toolbar perfect>
                <template #buttons>
                  <div class='smallToolTitle'>公共参数</div>
                  <vxe-input style='width: 130px' v-model='searchForm.searchValue' type='search' clearable class='vxeInputSearch' placeholder='关键字查询' @clear='findDictList' @keyup='keyupEnter'
                             @search-click='handleSearch(searchForm.searchValue)'></vxe-input>
                  <vxe-button type='text' class='button-blue' icon='vxe-icon-refresh' content='刷新' :loading='tloading' @click='findDictList'></vxe-button>
                  <vxe-button type='text' class='button-blue' icon='vxe-icon-square-plus' content='新建' @click='addDictDialog()'></vxe-button>
                  <vxe-button type='text' class='button-blue' icon='vxe-icon-edit' content='设置字段' @click='showDictData()'></vxe-button>
                  <vxe-button type='text' class='button-blue' icon='vxe-icon-search-zoom-in' content='设置属性' @click='showDetailData()'></vxe-button>
                </template>
              </vxe-toolbar>

              <div class='tableBox'>
                <vxe-table ref='dictTable' class='mytable-scrollbar' border='inner' align='center' height='auto'
                           :data='dictList' :loading='tloading'
                           :expand-config='{ expandAll: true, reserve: true }'
                           @current-change='dictRowClick'
                           :row-config='{ isCurrent: true, isHover: true }'
                           :column-config='{ resizable: true }'
                           :keyboard-config='{ isArrow: true, isTab: true, isEdit: true }'
                           resizable show-overflow keep-source>

                  <vxe-column field='code' title='参数编码' width='100'></vxe-column>
                  <vxe-column field='name' title='参数名称' width='130'></vxe-column>
                  <vxe-column field='isEdit' title='是否删改' width='180'>
                    <template #default='{ row, rowIndex, column }'>
                      <span>{{ row.isEdit === '1' ? '否' : '是' }}</span>
                    </template>
                  </vxe-column>
                  <vxe-column title='操作' fixed='right'>
                    <template #default='{ row }'>
                      <vxe-button type='text' status='primary' icon='vxe-icon-edit' circle @click.native='editDictDialog(row)' class='spanIcon'></vxe-button>
                      <vxe-button type='text' status='danger' icon='vxe-icon-delete' circle @click.native='deleteDict(row)' class='spanIcon'></vxe-button>
                    </template>
                  </vxe-column>
                </vxe-table>
              </div>


              <el-dialog title='参数配置' :show-close='false' v-model='showDialog' append-to-body width='500px' :close-on-click-modal='false'>
                <el-form ref='dictFormRef' :model='dictForm' :rules='dictFormRule' label-width='100px' class='form-input-m' inline-message @reset='resetDictForm'>
                  <el-row>
                    <el-col :span='24'>
                      <el-form-item prop='itemId' label='核算表单'>
                        <el-select v-model='dictForm.itemId' placeholder='下拉选择' style='width:200px'>
                          <el-option v-for='item in calcItemList' :key='item.id' :label='item.itemName' :value='item.id' />
                        </el-select>
                      </el-form-item>
                    </el-col>
                    <el-col :span='24'>
                      <el-form-item prop='code' label='参数编码'>
                        <el-input type='text' v-model='dictForm.code' placeholder='请输入参数编码' clearable></el-input>
                      </el-form-item>
                    </el-col>
                    <el-col :span='24'>
                      <el-form-item prop='name' label='参数名称'>
                        <el-input type='text' v-model='dictForm.name' placeholder='请输入参数名称' clearable></el-input>
                      </el-form-item>
                    </el-col>
                    <el-col :span='24'>
                      <el-form-item label='是否删改' prop='isActive'>
                        <el-switch v-model='dictForm.isEdit' inline-prompt active-text='是' inactive-text='否' active-value='0' inactive-value='1'></el-switch>
                      </el-form-item>
                    </el-col>
                    <el-col :span='24'>
                      <el-form-item prop='order' label='排序'>
                        <el-input-number v-model='dictForm.sx' :min='1' :max='1000' />
                      </el-form-item>
                    </el-col>
                  </el-row>
                </el-form>

                <div class='dialog-footer flex right justify-end'>
                  <el-button type='primary' @click="saveDict('dictFormRef')">保存</el-button>
                  <el-button @click="closeDialog('dictFormRef')">取消</el-button>
                </div>
              </el-dialog>
            </Pane>
            <Pane size='60'>
              <CalcBaseForm ref='dictChildRef' />
            </Pane>
          </Splitpanes>
        </el-tab-pane>
        <el-tab-pane label='操作日志'>
          <LogInfo requestUrl='/wk/calc/base'></LogInfo>
        </el-tab-pane>
      </el-tabs>
    </div>
  </div>
</template>

<script setup lang='ts'>
// 引入组件区 ==========
import Breadcrumb from '@/components/Breadcrumb.vue';
import { getCurrentInstance, onMounted, reactive, ref } from 'vue';
import { Pane, Splitpanes } from 'splitpanes';
import { AppStore } from '@/stores/store';
import { VxeMessage, VxeNotifyType } from '@/utils/CommonMessage';
import CalcBaseForm from './CalcBaseForm.vue';
import LogInfo from '@/components/LogInfo.vue'; //设置字段/属性 抽离组件

// 全局变量定义区 ==========
let { proxy }: any = getCurrentInstance();
let store = AppStore();

onMounted(() => {
  findDictList();
  findCalcItemList();
});

let searchForm = {
  searchValue: ''
};
let dictList: any = reactive([]); //中间字典字段table数据
let calcItemList: any = reactive([]); //中间字典字段table数据
let tloading = ref(false); //加载状态
let showDialog = ref(false);
let dictChildRef: any = ref(null); //最右侧点击设计模式/预览模式传值
// 条数/页
const PageSizeList = [10, 50, 100, 200, 500];
// 分页
let page = reactive({
  currentPage: 1,
  pageSize: PageSizeList[1],
  totalResult: 0
});
let dictForm = reactive({
  id: null,
  pid: null,
  itemId: '',
  orgId: '',
  code: '',
  name: '',
  isEdit: '0',
  grade: 0,
  sx: 0,
  value: '',
  bz: ''
});

let sltType: any = {};

// 清空中间字段弹框表单
function clearForm() {
  dictForm.id = null;
  dictForm.pid = '';
  dictForm.orgId = '';
  dictForm.code = '';
  dictForm.name = '';
  dictForm.isEdit = '0';
  dictForm.grade = 0;
  dictForm.sx = 0;
  dictForm.value = '';
  dictForm.bz = '';
}

/**
 * 新建公共参数
 */
function addDictDialog() {
  dictForm.pid = sltType.id;
  dictForm.sx = page.totalResult + 1;
  showDialog.value = true;
}

function findDictList() {
  tloading.value = true;
  dictList.length = 0; //放入数据前清空数据
  const url = '/wk/calc/base/page';
  proxy.$http
    //注意此处的数据条数
    .get(url, {
      params: { pid: sltType.id, pageIndex: page.currentPage, pageSize: page.pageSize, grade: 0 }
    })
    .then((res: any) => {
      dictList.push(...res.data.records);
      page.totalResult = res.data.total;
      dictRowClick({ row: dictList[0] }); //默认选中第一条数据
      tloading.value = false;
    })
    .catch((err: any) => {
      tloading.value = false;
      // VxeMessage('获取获取当前字典的字段列表失败',VxeNotifyType.error)
    });
}

function findCalcItemList() {
  proxy.$http.get('/wk/calc/item/getCalcItemList').then((res: any) => {
    calcItemList.push(...res.data);
  }).catch((err: any) => {
    proxy.$alert(err, '提示');
  });
}

/**
 * 中间编辑当前行字段
 * @param row
 */
function editDictDialog(row: any) {
  dictForm.id = row.id;
  dictForm.pid = row.pid;
  dictForm.orgId = row.orgId;
  dictForm.code = row.code;
  dictForm.name = row.name;
  dictForm.grade = row.grade;
  dictForm.isEdit = row.isEdit;
  dictForm.sx = row.sx;
  dictForm.value = row.value;
  dictForm.bz = row.bz;
  showDialog.value = true;
}

/**
 * 中间删除当前行字段
 * @param row
 */
function deleteDict(row: any) {
  proxy
    .$confirm('确定删除此字段？', '提示', {
      cancelButtonClass: 'cancel-button',
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    })
    .then(async () => {
      const url = '/api/sys/basDict/deleteDict';
      proxy.$http.post(url, row).then((res: any) => {
        if (res.status.code === 1) {
          findDictList();
          VxeMessage('删除字段成功', VxeNotifyType.success);
        } else {
          VxeMessage(res.status.msg, VxeNotifyType.error);
        }
      });
    })
    .catch((err: any) => {
      // VxeMessage(err, VxeNotifyType.error);
    });
}

/**
 * 中间字段弹框保存
 * @param formName
 */
function saveDict(formName: any) {
  let $el = proxy.$refs[formName];
  $el.validate((valid: any) => {
    if (!valid) {
      return false;
    }
    if (dictForm.id === null) {
      const url = '/wk/calc/base/add';
      const user = {
        code: dictForm.code,
        name: dictForm.name,
        pid: dictForm.pid,
        grade: 0,
        sx: dictForm.sx,
        isEdit: dictForm.isEdit,
        itemId: dictForm.itemId,
        bz: dictForm.bz,
        orgId: store.userInfo.orgId
      };
      proxy.$http.post(url, user).then((res: any) => {
        VxeMessage('新增字段成功', VxeNotifyType.success);
        clearForm();
        showDialog.value = false;
        findDictList();
      }).catch((err: any) => {
        VxeMessage('新增字段失败', VxeNotifyType.error);
      });
    } else {
      // 修改用户
      const url = '/wk/calc/base/update';
      const user = {
        id: dictForm.id,
        code: dictForm.code,
        name: dictForm.name,
        grade: 0,
        sx: dictForm.sx,
        isEdit: dictForm.isEdit,
        bz: dictForm.bz,
        orgId: dictForm.orgId
      };
      proxy.$http.post(url, user).then((res: any) => {
        VxeMessage('修改字段成功', VxeNotifyType.success);
        setTimeout(() => {
          clearForm();
          showDialog.value = false;
          findDictList();
        }, 500);
      }).catch((err: any) => {
        VxeMessage('修改字段失败', VxeNotifyType.error);
      });
    }
  });
}

// 点击字段当前行触发的事件
function dictRowClick({ row }: any) {
  (proxy.$refs.dictTable as any).setCurrentRow(row);
  dictChildRef.value.initPage(row); //给最右侧传值
}

/**
 * 中间字段弹框取消按钮
 * @param formMiddleName
 */
function closeDialog(formMiddleName: any) {
  const el: any = proxy.$refs[formMiddleName];
  // 移除校验结果
  el.clearValidate();
  clearForm();
  showDialog.value = false;
}

/**
 * 设计模式
 */
function showDictData() {
  dictChildRef.value.showDictData();
}

/**
 * 预览模式
 */
function showDetailData() {
  dictChildRef.value.showDetailData();
}
</script>

<style lang='scss' scoped>
#CalcBase {
  height: 100%;

  .bodyContent {
    height: calc(100% - 60px);

    .el-tabs {
      height: 100%;

      :deep(.el-tabs__content) {
        height: calc(100% - 39px);
        padding: 0px;

        .el-tab-pane {
          height: 100%;
        }
      }
    }

    .area {
      background-color: $base-white;
    }

    // 附加按钮间距
    .button-blue,
    .button-red {
      margin: 5px 0 5px 5px;
    }

    .tableBox {
      height: calc(100% - 40px);

      .vxe-table {
        height: 100%;

        :deep(.vxe-table--render-wrapper) {
          height: 100%;

          .vxe-table--main-wrapper {
            height: 100%;

            .vxe-table--body-wrapper {
              height: calc(100% - 26px) !important;
            }
          }
        }
      }
    }
  }
}
</style>

